
package com.tideit.husai

import android.os.Bundle
import android.content.pm.PackageManager
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.tideit.husai.databinding.ActivityMainBinding
import com.tideit.husai.ui.attack.AttackSimulationFragment
import com.tideit.husai.ui.battle.BattleStatusFragment
import com.tideit.husai.ui.chat.ChatFragment
import com.tideit.husai.ui.watch.WatchModeFragment

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // 检查权限
        if (checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION), 1)
        }

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // 设置默认Fragment
        if (savedInstanceState == null) {
            supportFragmentManager.beginTransaction()
                .replace(R.id.fragment_container, BattleStatusFragment())
                .commit()
        }

        // 底部导航点击事件
        binding.bottomNav.setOnNavigationItemSelectedListener { item ->
            val selectedFragment: Fragment = when (item.itemId) {
                R.id.nav_attack -> {
                    android.util.Log.d("MainActivity", "创建AttackSimulationFragment")
                    AttackSimulationFragment()
                }
                R.id.nav_watch -> {
                    android.util.Log.d("MainActivity", "创建WatchModeFragment")
                    WatchModeFragment()
                }
                R.id.nav_chat -> {
                    android.util.Log.d("MainActivity", "创建ChatFragment")
                    ChatFragment()
                }
                else -> {
                    android.util.Log.d("MainActivity", "创建默认BattleStatusFragment")
                    BattleStatusFragment()
                }
            }
            supportFragmentManager.beginTransaction()
                .replace(R.id.fragment_container, selectedFragment)
                .addToBackStack(null)
                .commit()
            true
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            1 -> {
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    android.util.Log.d("MainActivity", "位置权限已授予")
                } else {
                    android.util.Log.w("MainActivity", "位置权限被拒绝")
                }
            }
        }
    }
}
